package com.leetcode.partition4;

import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2021/8/26 8:56
 */
public class LC392判断子序列 {

    public static boolean isSubsequence(String s, String t) {
//        return dynamicProgramming(s, t);
        return doubleIndex(s, t);
    }

    public static void main(String[] args) {
        String s = "b";
        String t = "abc";
        System.out.println(isSubsequence(s, t));
    }

    private static boolean doubleIndex(String s, String t) {
        if ("".equals(s)) return true;
        int i = 0, j = 0;
        while (i < s.length() && j < t.length()) {
            if (s.charAt(i) == t.charAt(j)) i++;        //如果两个字符都相同就同时移动两个的指针
            j++;            //如果两个字符不相等，只需要移动t的指针j，让i指针继续指向s与j进行匹配
        }
        return i == s.length();
    }

    private static boolean dynamicProgramming(String s, String t) {
        //转换为求两个字符串的最长公共子序列，dp[i][j]：字符串s[0, i-1]和字符串t[0, j-1]的最长公共子序列
        int[][] dp = new int[s.length() + 1][t.length() + 1];
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 1; j <= t.length(); j++) {
                if (s.charAt(i - 1) == t.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j - 1], dp[i][j - 1]);
                }
            }
        }
        Arrays.stream(dp).forEach(item -> System.out.println(Arrays.toString(item)));
        return dp[s.length()][t.length()] == s.length();
    }

}
